package com.briup.smartcity_group6.service.Impl;


import com.briup.smartcity_group6.bean.basic.Category;
import com.briup.smartcity_group6.dao.basic.CategoryMapper;
import com.briup.smartcity_group6.dao.ext.CategoryExtMapper;
import com.briup.smartcity_group6.exception.ServiceException;
import com.briup.smartcity_group6.service.ICategoryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryExtMapper categoryExtMapper;

    public void deleteById(Integer id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        if (category==null){
            throw new ServiceException("id不存在");
        }
         List keys =categoryExtMapper.findIdByParentId(id);
        for (int i = 0; i < keys.size(); i++) {
            categoryMapper.deleteByPrimaryKey((Integer) keys.get(i));
        }
        categoryMapper.deleteByPrimaryKey(id);
       //categoryExtMapper.deleteByCategoryParentId(id);

    }

    public void deleteMany(List<Integer> list) {
        for (int i = 0; i < list.size(); i++) {
            Category category = categoryMapper.selectByPrimaryKey(list.get(i));
            if (category==null){
                throw new ServiceException("有id不存在");
            }
        }
        for (int i = 0; i < list.size(); i++) {
            List keys =categoryExtMapper.findIdByParentId(list.get(i));
            for (int j = 0; j < keys.size(); j++) {
                categoryMapper.deleteByPrimaryKey((Integer) keys.get(j));
            }
            categoryMapper.deleteByPrimaryKey(list.get(i));
        }
    }

    public List<Category>selectAll() {
        List<Category> categories = categoryExtMapper.selectAll();
        return categories;

    }
//
    public PageInfo<Category> finfAll(int PageNum, int PageSize) {
        //java8写法：
        PageInfo<Category> pageInfo = PageHelper.startPage(PageNum, PageSize, true).doSelectPageInfo(
                () -> categoryExtMapper.selectAll()
        );
        return pageInfo;
    }

    public void addCategory(Category category) {
       Category category1=categoryMapper.selectByPrimaryKey( category.getCategoryId());
       if (!(category1==null)){
           throw new ServiceException("id重复");
        }
       categoryMapper.insertSelective(category);

    }


    public void updateCategory(Category category) {
        categoryMapper.updateByPrimaryKeySelective(category);
    }
}
